import os
from PyQt5.QtWidgets import QFileDialog, QMessageBox, QTreeView
from PyQt5.QtGui import QStandardItemModel, QStandardItem
from PyQt5.QtCore import QDir, Qt

class FileOperations:
    def __init__(self, parent):
        self.parent = parent
        self.current_folder = None
        
        # 创建文件树模型
        self.file_model = QStandardItemModel()
        self.file_model.setHorizontalHeaderLabels(['项目文件'])
        
        # 创建文件树视图
        self.file_tree = QTreeView()
        self.file_tree.setModel(self.file_model)
        
    def get_file_tree(self):
        return self.file_tree
        
    def open_file(self):
        """打开单个文件"""
        file_path, _ = QFileDialog.getOpenFileName(self.parent, "打开文件", "", "所有文件 (*.*)")
        if file_path:
            try:
                with open(file_path, 'r', encoding='utf-8') as file:
                    content = file.read()
                    return content, None
            except Exception as e:
                return None, str(e)
        return None, None
    
    def open_folder(self):
        """打开文件夹作为工作区"""
        folder_path = QFileDialog.getExistingDirectory(self.parent, "打开文件夹")
        if folder_path:
            self.current_folder = folder_path
            self.update_file_tree(folder_path)
    
    def remove_workspace(self):
        """移除当前工作区"""
        if self.current_folder:
            reply = QMessageBox.question(
                self.parent, 
                '确认移除', 
                '确定要移除当前工作区吗？\n这不会删除文件夹中的实际文件。',
                QMessageBox.Yes | QMessageBox.No, 
                QMessageBox.No
            )
            
            if reply == QMessageBox.Yes:
                self.current_folder = None
                self.file_model.clear()
                self.file_model.setHorizontalHeaderLabels(['项目文件'])
                return True
        else:
            QMessageBox.information(self.parent, '提示', '当前没有打开的工作区')
        return False
    
    def update_file_tree(self, path):
        """更新文件树显示"""
        self.file_model.clear()
        self.file_model.setHorizontalHeaderLabels(['项目文件'])
        root_item = self.file_model.invisibleRootItem()
        self.add_directory_items(root_item, path)
    
    def add_directory_items(self, parent_item, path):
        """递归添加目录项到文件树"""
        directory = QDir(path)
        for entry in directory.entryInfoList(QDir.AllEntries | QDir.NoDotAndDotDot):
            item = QStandardItem(entry.fileName())
            item.setData(entry.filePath(), Qt.UserRole)
            parent_item.appendRow(item)
            if entry.isDir():
                self.add_directory_items(item, entry.filePath())
    
    def get_file_content(self, index):
        """获取文件内容"""
        file_path = self.file_model.data(index, Qt.UserRole)
        if os.path.isfile(file_path):
            try:
                with open(file_path, 'r', encoding='utf-8') as file:
                    content = file.read()
                    return content, None
            except Exception as e:
                return None, str(e)
        return None, None